package com.coffee.attachment;

import cn.hutool.core.util.StrUtil;
import com.coffee.attachment.entity.AttachDocumentEntity;
import com.coffee.attachment.service.MochaAttachmentService;
import com.coffee.attachment.service.MochaExcelService;
import com.coffee.core.CoffeeResponse;
import com.coffee.excel.MochaExcel;
import com.coffee.excel.MochaExcelSheet;
import com.coffee.minio.MochaMinioTemplate;
import com.coffee.minio.args.MochaBaseArgs;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author: songkui
 * @since: 2023/4/20 15:34
 */
@Slf4j
@RestController
@RequestMapping("/coffee/excel-download")
@AllArgsConstructor
public class CoffeeExcelEndpoint {
    private final MochaExcelService mochaExcelService;
    private final MochaAttachmentService mochaAttachmentService;
    private final MochaMinioTemplate mochaMinioTemplate;

    /**
     * 下载导入模板
     * @param excelCode
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/importTemplate/{excelCode}")
    public ResponseEntity<Resource> downloadImportTemplate(@PathVariable("excelCode") String excelCode) throws UnsupportedEncodingException {
        if (StrUtil.isEmpty(excelCode)){
            return ResponseEntity.status(HttpStatus.PRECONDITION_REQUIRED).build();
        }

        MochaExcelSheet sheet =  mochaExcelService.findExcelField(excelCode, null);
        if (null == sheet){
            log.error("{} import template not mapping ", excelCode);
            return ResponseEntity.status(HttpStatus.PRECONDITION_REQUIRED).build();
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        MochaExcel.importTemplate(sheet.getFieldList(), sheet.getTitle())
                .outputStream(outputStream)
                .doImportTemplate();
        byte[] bytes = outputStream.toByteArray();
        Resource resource = new ByteArrayResource(bytes);
        String fileName = sheet.getTitle()+"_导入模板.xlsx";
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment;filename="+URLEncoder.encode(fileName, "UTF-8")+ ";filename*=utf-8''"
                                + URLEncoder.encode(fileName, "UTF-8"))
                .body(resource);

    }

    /**
     * 文档列表下载文件  eg. 导出excel数据
     * @param documentId
     * @return
     * @throws Exception
     */
    @GetMapping("/document/{documentId}")
    public ResponseEntity<Resource> downloadDocument(@PathVariable("documentId") Integer documentId) throws  Exception{
        AttachDocumentEntity entity = mochaAttachmentService.getDocumentById(documentId);
        if (null == entity || !entity.checkMinio()){
            return ResponseEntity.status(HttpStatus.PRECONDITION_REQUIRED).build();
        }

        byte[] bytes = mochaMinioTemplate.getObjectStream(new MochaBaseArgs(entity.getMinioBucket(), entity.getMinioObject()));
        //1,更改 展示次数； 2，写入日志；
        Resource resource = new ByteArrayResource(bytes);
        String fileName = entity.buildFileName();
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment;filename="+URLEncoder.encode(fileName, "UTF-8")+ ";filename*=utf-8''"
                                + URLEncoder.encode(fileName, "UTF-8"))
                .body(resource);

    }


}
